(function ($) {
    $.fn.extend({
        serializeObject: function () {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        }
    });

})(jQuery);

function loadPageByIdAndUri(id, uri) {
    $("#" + id).load(uri);

}

function loadMainBody(uri) {
    loadPageByIdAndUri('main', uri);
}

function loadPage(id) {
    loadPageByIdAndUri(id, id);
}

/**
 * 保存电影信息
 */
function saveMovie() {
    if (document.movieForm["typeId"].value === "" || document.movieForm["languageId"].value === "") {
        return alert("电影类型或电影语言不能为空!");
    }
    var imageFile = document.getElementById('imageFile').files[0];
    var videoFile = document.getElementById('videoFile').files[0];
    var form = new FormData(document.getElementById('movieFormId'));
    if (imageFile === undefined) {
        if (document.movieForm.imageFileName.value === "") {
            alert("电影封面图片不能为空");
            return;
        }
    } else {
        form.append("imageFile", imageFile);

    }
    if (videoFile === undefined) {
        if (document.movieForm.videoFileName.value === "") {
            alert("电影视频文件不能为空");
            return;
        }
    } else {
        form.append("videoFile", videoFile);
    }
    $.ajax({
        type: "POST",
        url: "/admin/movie/save",
        data: form,
        processData: false,
        contentType: false,
        success: function () {
            loadMainBody('/admin/movie/list');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var error = XMLHttpRequest['responseJSON'].errors[0]['defaultMessage'];
            alert(error);
        }
    });
}

/**
 * 保存电影类型
 */
function saveMovieType() {
    var id = document.movieTypeForm.typeId.value;
    var typeName = document.movieTypeForm.typeName.value;
    if (typeName.length === 0) return;
    var data = [{name: "id", value: id}, {name: "typeName", value: typeName}];
    if (!checkObjIsExist(id, typeName, "/admin/movie/type")) {
        $.ajax({
            type: "POST",
            url: "/admin/movie/type/save",
            data: data,
            success: function () {
                loadMainBody('/admin/movie/type/list');
            }

        });
    }

}

/**
 * 保存电影语言
 */
function saveMovieLanguage() {
    var id = document.movieLanguageForm.languageId.value;
    var language = document.movieLanguageForm.language.value;
    if (language.length === 0) return;
    var data = [{name: "id", value: id}, {name: "language", value: language}];
    if (!checkObjIsExist(id, language, "/admin/movie/language")) {
        $.ajax({
            type: "POST",
            url: "/admin/movie/language/save",
            data: data,
            success: function (result) {
                if (result) {
                    loadMainBody('/admin/movie/language/list');
                }
            }
        })
        ;
    }
}

/**
 * 保存管理员
 */
function saveAdmin() {
    if (!checkAccountIsExist()) {
        var data = $("#add_admin_form").serializeArray();
        var rawPassword = $("#raw-password").val();
        var password = $("#password").val();
        if (rawPassword !== password) {
            password = hex_md5(password);
        }
        data.push({name: "password", value: password});
        $.ajax({
            type: "POST",
            url: "/admin/save",
            data: data,
            success: function () {
                loadMainBody('list');
            }
        });
    }
}

/**
 * 保存人物
 */
function savePerson() {
    var form = new FormData(document.getElementById("personFormId"));
    var imageFile = document.getElementById("imageFile").files[0];
    if (imageFile !== undefined) {
        form.append("imageFile", imageFile);
    }
    var options = $("#birthPlace select").find("option:selected");
    $.each(options, function (i, item) {
        var name = item.parentElement.getAttribute("id");
        var code = item.getAttribute("data-code");
        form.append(name, code);
    });
    $.ajax({
        type: "POST",
        url: "/admin/person/save",
        data: form,
        processData: false,
        contentType: false,
        success: function () {
            loadMainBody('/admin/person/list');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var error = XMLHttpRequest['responseJSON'].errors[0]['defaultMessage'];
            alert(error);
        }
    });
}

/**
 * 保存新闻
 */
function saveMovieNews() {
    var form = new FormData(document.getElementById("movieNewsFormId"));
    var imageFile = document.getElementById("imageFile").files[0];
    if (imageFile !== undefined) {
        form.append("imageFile", imageFile);
    }
    var content = ckEditor.document.getBody().getHtml();
    form.append("content", content);
    $.ajax({
        type: "POST",
        url: "/admin/movie/news/save",
        data: form,
        processData: false,
        contentType: false,
        success: function () {
            loadMainBody('/admin/movie/news/list');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var error = XMLHttpRequest['responseJSON'].errors[0]['defaultMessage'];
            alert(error);
        }
    });
}

/**
 * 判断对象是否存在
 * 例如 id = 123 , name = 'jack' , uri = '/movie/type/'
 */
function checkObjIsExist(id, name, uri) {
    var url = uri + "/exist?id=" + id + "&name=" + name;
    var isExist = false;
    $.ajax({
        url: url,
        async: false,
        success: function (msg) {
            var display = msg ? "inline" : "none";
            $(".span-exist-tip").css("display", display);
            isExist = msg;
        }
    });
    return isExist;
}

/**
 * 判断帐号是否存在
 */
function checkAccountIsExist() {
    var id = $("#adminId").val();
    var account = $("#account").val();
    var url = "/admin/exist?account=" + account + "&id=" + id;
    var isExist = false;
    $.ajax({
        url: url,
        async: false,
        success: function (msg) {
            var display = msg ? "inline" : "none";
            $(".span-exist-tip").css("display", display);
            isExist = msg;
        }
    });
    return isExist;
}


/**
 * 删除指定数据
 * @param uri 要删除的uri地址
 * @param successUri 删除成功回调地址
 */
function deleteObj(uri, successUri) {
    $.ajax({
        type: "delete",
        url: uri,
        success: function () {
            loadMainBody(successUri);
        }
    });
}

function deleteAllObj(uri, successUri, classId) {
    var idArr = new Array();
    var idStr = "";
    $("." + classId).each(function () {
        if ($(this).prop("checked")) {
            var id = $(this).attr("objId");
            idArr.push(id);
            idStr += "id=" + id + "&";
        }
    });

    if (idStr.length > 0) {
        idStr = idStr.substr(0, idStr.lastIndexOf("&"));
        $.ajax({
            type: "delete",
            url: uri + "?" + idStr,
            dataType: 'text',
            success: function () {
                loadMainBody(successUri);
            }
        });

    }

}


var initPlaceSelect = function (province, city, district) {
    var $distpicker = $('#distpicker');

    $distpicker.distpicker({
        province: province,
        city: city,
        district: district
    });

    $('#reset').click(function () {
        $distpicker.distpicker('reset');
    });

    $('#reset-deep').click(function () {
        $distpicker.distpicker('reset', true);
    });

    $('#destroy').click(function () {
        $distpicker.distpicker('destroy');
    });

    $('#distpicker').distpicker({
        placeholder: false
    });

};

/**
 * 使选择框的选中状态与父选择框一致
 * @param id
 * @param childClass
 */
function setCheckBox(id, childClass) {
    var isChecked = $("#" + id).prop("checked");
    $("." + childClass).prop("checked", isChecked);
}

/**
 * 退出后台
 */
function logoutBackground() {
    $.get("/admin/logout", function (msg) {
        if (msg === "true") {
            window.location.href = "/admin/login/form";
        } else {
            alert("退出异常!");
        }
    });

}

function loadMovieHeader() {
    loadPageByIdAndUri('movie-header', "/movie/movie-header");
}

function loadMovieFooter() {
    loadPageByIdAndUri('movie-footer', "/movie/movie-footer");
}

function loadUserFragment(uri, page) {
    loadPageByIdAndUri('user-fragment', uri + "?page=" + page + "&size=10");
}

function setUserFragmentActive(index) {
    var lis = $(".user-fav ul li");
    for (var i = 0; i < lis.length; i++) {
        lis.eq(i).attr("class", "");
    }
    lis.eq(index).attr("class", "active");
}